package org.ysling.litemall.db.service;

import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.ysling.litemall.db.dao.LitemallTenantMapper;
import org.ysling.litemall.db.domain.LitemallStorage;
import org.ysling.litemall.db.domain.LitemallTenant;
import org.ysling.litemall.db.domain.LitemallTimeline;
import org.ysling.litemall.db.example.LitemallTenantExample;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
@CacheConfig(cacheNames = "tenant")
public class LitemallTenantService {

    @Resource
    private LitemallTenantMapper tenantMapper;

    @CacheEvict(allEntries = true)
    public Integer add(LitemallTenant tenant) {
        tenant.setAddTime(LocalDateTime.now());
        tenant.setUpdateTime(LocalDateTime.now());
        return tenantMapper.insertSelective(tenant);
    }

    @Cacheable(sync = true)
    public int count() {
        LitemallTenantExample example = new LitemallTenantExample();
        example.or().andDeletedEqualTo(false);
        return (int) tenantMapper.countByExample(example);
    }

    @Cacheable(sync = true)
    public List<LitemallTenant> queryList(Integer page, Integer limit) {
        LitemallTenantExample example = new LitemallTenantExample();
        example.or().andDeletedEqualTo(false);
        example.setOrderByClause(LitemallTimeline.Column.addTime.desc());
        PageHelper.startPage(page, limit);
        return tenantMapper.selectByExample(example);
    }

    @Cacheable(sync = true)
    public List<LitemallTenant> queryList() {
        LitemallTenantExample example = new LitemallTenantExample();
        example.or().andDeletedEqualTo(false);
        example.setOrderByClause(LitemallTimeline.Column.addTime.desc());
        return tenantMapper.selectByExample(example);
    }

    @CacheEvict(allEntries = true)
    public int updateById(LitemallTenant tenant) {
        tenant.setUpdateTime(LocalDateTime.now());
        return tenantMapper.updateByPrimaryKeySelective(tenant);
    }

    @CacheEvict(allEntries = true)
    public int updateVersionSelective(LitemallTenant tenant) {
        tenant.setUpdateTime(LocalDateTime.now());
        return tenantMapper.updateWithVersionByPrimaryKeySelective(tenant.getVersion(), tenant);
    }

    @CacheEvict(allEntries = true)
    public void deleteById(Integer id) {
        LitemallTenantExample example = new LitemallTenantExample();
        example.or().andIdEqualTo(id);
        tenantMapper.logicalDeleteByExample(example);
    }
}
